package com.adinall.dsp.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import com.adinall.dsp.core.globle.Constants;
import com.adinall.dsp.core.utils.ClientUtils;
import com.adinall.dsp.core.utils.CollectionUtils;
import com.adinall.dsp.core.utils.StringUtils;
import com.adinall.dsp.core.web.interceptor.MainInterceptor;

/**
 * 请求日志用拦截器
 * 
 * @author 高万超
 * @version V1.0.0 $ 2017年9月8日 下午2:14:33
 */
public class LogInterceptor extends MainInterceptor {

    private Logger logger = LogManager.getLogger(getClass());

    private ThreadLocal<Long> times = new ThreadLocal<>();

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

        times.set(System.currentTimeMillis());

        if (logger.isInfoEnabled()) {
            logger.info(clientInfo(request) + " --> " + getHandlerObj(obj) + "[" + (System.currentTimeMillis() - times.get()) + "ms] start.... ");
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView view) throws Exception {

        if (logger.isInfoEnabled()) {
            logger.info(clientInfo(request) + " --> " + getHandlerObj(obj) + "[" + (System.currentTimeMillis() - times.get()) + "ms] - JAVA");
        }
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception) throws Exception {

        if (logger.isInfoEnabled()) {
            logger.info(clientInfo(request) + " --> " + getHandlerObj(obj) + "[" + (System.currentTimeMillis() - times.get()) + "ms] - PAGE");
        }
    }

    private String getHandlerObj(Object obj) {

        String handlerObj = StringUtils.toString(obj);
        if (obj instanceof HandlerMethod) {

            HandlerMethod hm = (HandlerMethod) obj;
            handlerObj = hm.getBeanType().getName() + "#" + hm.getMethod().getName();
        }

        return handlerObj;
    }

    private String clientInfo(HttpServletRequest request) {

        StringBuffer buf = new StringBuffer();
        buf.append("[");

        try {
            String username = Constants.BLANK;
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal instanceof UserDetails) {
                username = ((UserDetails) principal).getUsername();
            } else {
                username = principal.toString();
            }
            buf.append(username);
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.warn("用户未登录");
        }
        buf.append("(");
        buf.append(ClientUtils.getRemoteAddress(request));
        buf.append(")");
        buf.append("]");

        buf.append("[");
        buf.append(request.getServletPath() + "?");
        buf.append(CollectionUtils.join(request.getParameterMap(), "&"));
        buf.append("]");

        return StringUtils.toString(buf);
    }
}
